#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import re
import urllib
from xml.etree import cElementTree as ET

__all__ = ["VERSION", "NAME", "TITLE",
           "album_list_uri", "parse_album_list", "album_list_page_uri",
           "parse_photo_list"]

VERSION = "0.0.0.1"
NAME = "yandex.ru"
TITLE = u"Фотки на yandex.ru"


def album_list_uri(user, **kwargs):
    """Make album list uri for specified user.

    returns:
        dict
    At least items below are returned:

    `url` : str
        URL for album list
    `user` : str
        username of album owner

    Optional:
        `multipage` : bool
            if multiple pages found
    """
    r = {
        'url': 'http://api-fotki.yandex.ru/api/users/%(user)s/albums/' % locals(),
        'multipage': False,
        'user': user
    }
    return r

def album_list_page_uri(user, page, **kwargs):

    return album_list_uri(user, **kwargs)

def parse_album_list(atom, **kwargs):
    """
    Returns dict of kwargs +

    `next_page` : str
        URI for next page if present
    `multipage` : bool
        True if next page available
    `albums` : list-of-tuple
        (url, title, image-count) per album entry
    """
    #R = re.compile(u'<entry>.*?urn:yandex:fotki:%(user)s:album:(?P<album>.*?)</id>.*?<title>(?P<title>.*?)</title>.*?</entry>' % kwargs, re.I|re.U|re.S)
    ret = kwargs or {}
    ret['albums'] = []
    try:
        xml = ET.fromstring(atom)
        try:
            next = [n.get('href') for n in xml.findall(u'{http://www.w3.org/2005/Atom}link') if n.get('rel')==u'next'][0]
            ret['next_page'] = next
            ret['multipage'] = True
        except:
            next = False
            ret['multipage'] = False
            ret['next_page'] = ''

        xitm = xml.findall('{http://www.w3.org/2005/Atom}entry')
        for x in xitm:
            tit = x.find('{http://www.w3.org/2005/Atom}title').text
            url = [a for a in x.findall('{http://www.w3.org/2005/Atom}link') if a.get('rel','')=='photos']
            url = url[0].get('href','') if  url else ''
            try:
                cnt = x.find('{yandex:fotki}image-count').get('value')
            except:
                cnt = 0

            ret['albums'].append((url, tit, cnt))

    except Exception, e:
        print "yandex.ru album list error: %s" % (e,)
        pass
    #ret['albums'] = [('http://api-fotki.yandex.ru/api/users/%s/album/%s/photos/' % (ret['user'], x[0]), x[1]) for x in R.findall(html)]
    #ret['album'] = R.search(html).group('album')
    return ret

def parse_photo_list(atom, **kwargs):
    #R = re.compile(u'<entry>.*?<title>(?P<title>.*?)</title>.*?<content\s+src="(?P<img>.*?)_XL".*?</entry>', re.I|re.S|re.U)
    #phs = R.findall(rss)
    ret = kwargs
    ret['photos'] = []
    try:
        xml = ET.fromstring(atom)
        try:
            cnt = int(xml.find(u'{yandex:fotki}image-count').get('value'))
        except:
            cnt = 100
        try:
            next = [n.get('href') for n in xml.findall(u'{http://www.w3.org/2005/Atom}link') if n.get('rel')==u'next'][0]
            ret['next_page'] = next
        except:
            print "no-next"
            next = False
        if next:
            ret['page_count'] = (cnt / 100) + 1
            ret['multipage'] = True
        else:
            ret['next_page'] = ''

        for x in xml.findall('{http://www.w3.org/2005/Atom}entry'):
            acc = x.find('{yandex:fotki}access').get('value')
            url = x.find('{http://www.w3.org/2005/Atom}content').get('src').replace('_XL', '_orig')
            title = x.find('{http://www.w3.org/2005/Atom}title').text
            if acc != 'private':
                ret['photos'].append({
                    'title': u"%s" % (title or os.path.basename(url)[:-5]),
                    'full': url,
                })
    except:
        return ret

    return ret

    r = []
    loc = {}
    loc.update(kwargs)

    for title, img in phs:
        #loc['album'] = alb
        loc['title'] = title
        loc['img'] = os.path.basename(img)
        r.append({
            'title': u"%s_%s" % (title, os.path.basename(img)),
            'full': '%s_orig' % (img,)
            }
        )

    ret['photos'] = r
    return ret


if __name__ == "__main__":
    pass
